package ru.aslanov.schedule.server.services;

import ru.aslanov.schedule.model.DataItem;
import ru.aslanov.schedule.model.GoogleCalendarSync;
import ru.aslanov.schedule.model.Operation;
import ru.aslanov.schedule.server.AccessDeniedException;
import ru.aslanov.schedule.server.AccessManager;
import ru.aslanov.schedule.utils.XMLUtil;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.xml.datatype.DatatypeConstants;

/**
 * Created by IntelliJ IDEA.
 * Created: Mar 4, 2010 1:12:46 PM
 *
 * @author Sergey Aslanov
 */
public class GoogleCalendarSyncService extends ScheduleChildService<GoogleCalendarSync> {

    public GoogleCalendarSyncService() {
        super(null);
    }

    @Override
    protected Class<GoogleCalendarSync> getEntityClass() {
        return GoogleCalendarSync.class;
    }

    @Override
    protected void fillDataItem(DataItem dataItem, GoogleCalendarSync object, HttpServletRequest request, PersistenceManager pm) throws Exception {
        super.fillDataItem(dataItem, object, request, pm);
        setAttr(dataItem, "hasSessionToken", object.getSessionToken() != null);
        setAttr(dataItem, "authorizedByUser", object.getAuthorizedByUser());
        setAttr(dataItem, "lastPublishDate", XMLUtil.date2XmlDate(object.getLastPublishDate(), DatatypeConstants.DATETIME));
        setAttr(dataItem, "lastPublishErrors", object.getLastPublishErrors());
        setAttr(dataItem, "syncStatus", object.getSyncStatus());
    }

    @Override
    protected boolean checkPermission(GoogleCalendarSync existingEntity, HttpServletRequest request, PersistenceManager pm, Operation operation) throws AccessDeniedException {
        AccessManager am = AccessManager.getInstance();
        if (operation == Operation.VIEW) {
            return am.isScheduleAdmin(getParentKey(request));
        } else {
            throw new AccessDeniedException(request);
        }
    }

    @Override
    protected void makeObjectPersistent(PersistenceManager pm, GoogleCalendarSync object, HttpServletRequest request) {
        throw new UnsupportedOperationException();
    }
}
